from dataclasses import dataclass

from src.application.user.enums import LangCode
from src.application.user.uow import UserUoW
from src.domain.user.value_objects import TelegramUserId


@dataclass(frozen=True)
class ChangeUserLang:
    tg_user_id: int
    lang_code: str


class ChangeUserLangHandler:
    """Смена языка пользователя"""

    def __init__(self, *, uow: UserUoW) -> None:
        self._uow = uow

    async def __call__(self, command: ChangeUserLang) -> None:
        user_id = TelegramUserId(value=command.tg_user_id)
        lang_code = getattr(LangCode, command.lang_code)

        user = await self._uow.user_repo.acquire_user_by_id(user_tg_id=user_id)

        user.set_language(lang_code)

        try:
            await self._uow.user_repo.update_user(user=user)
        except Exception as err:
            await self._uow.rollback()
            raise err

        await self._uow.commit()
